package edu.hawaii.duedates.libraries;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import com.meterware.httpunit.GetMethodWebRequest;
import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebRequest;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * UH Manoa Library information will be generated from this class.
 * 
 * @author Ka Hung Phillip Lau
 * @author Creighton Okada
 * 
 */
public class UhManoaLibrary {
  /**
   * Attempts to login to UH Manoa Library system.
   * 
   * @param id The UH user ID.
   * @param lastName The UH user's last name.
   * @return The WebConversation instance after successful login.
   * @throws Exception If login was not successful with these credentials.
   */
  WebConversation loginToUhLibrary(String id, String lastName) throws Exception {
    String url = "http://uhmanoa.lib.hawaii.edu/cgi-bin/Pwebrecon.cgi?DB=local&PAGE=pbLogon";
    // UH Library Website has bogus JavaScript code.
    HttpUnitOptions.setExceptionsThrownOnScriptError(false);
    // create the conversation object which will maintain state for us
    WebConversation conversation = new WebConversation();
    WebRequest request = new GetMethodWebRequest(url);
    WebResponse response = conversation.getResponse(request);
    WebForm form = response.getFormWithName("logonpage");
    form.setParameter("BC", id);
    form.setParameter("LN", lastName);
    form.submit();
    response = conversation.getCurrentPage();
    if (response.getText().contains(
        "Sorry, Login unsuccessful.  Username and/or password" + " is not correct")) {
      throw new Exception("Error while logging in to UH Library");
    }
    return conversation;
  }

  /**
   * Given a logged in user to the UH Library site, provides info about their library books.
   * 
   * @param id The UH user ID.
   * @param lastName The UH user's last name.
   * @return A String containing information about their books.
   * @throws Exception If problems occur parsing the site pages.
   */
  public List<LibraryBook> getUhInfo(String id, String lastName) throws Exception {
    String uhSiteNoItemString = "You have no items checked out.";
    List<LibraryBook> books = new ArrayList<LibraryBook>();
    try {
      WebConversation conversation = this.loginToUhLibrary(id, lastName);
      WebResponse response = conversation.getCurrentPage();
      WebForm form = response.getForms()[0];
      if (uhSiteNoItemString.equals(form.getText())) {
        System.out.println("No Books Checked Out.");
        return books;
      }
      else {

        boolean noBooksOut = response.getText().contains("Item");

        if (noBooksOut) {
          WebTable table = response.getTableStartingWith("Item");
          DateFormat newFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
          String tempDate = null;
          for (int a = 0; a < table.getRowCount(); a++) {
            tempDate = (table.getCellAsText(a, 3).substring(18));
            Date date = newFormat.parse(tempDate);
            LibraryBook tempBook = new LibraryBook(table.getCellAsText(a, 1), date);
            books.add(tempBook);
          }
        }
        return books;
      }
    }
    catch (Exception e) {
      throw new Exception("Error getting UH Book info", e);
    }
  }
}
